import logging, exceptions, time, datetime, base64
from google.appengine.ext import webapp
from controllers import controller
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from config import *
from models import *

from lib import GoogleS3

class EmailReceiver(controller.Controller, InboundMailHandler):
  
    def receive(self, message):
      logging.info("#### EmailReceiver.receive["+message.sender+"]")
      
      if not self.is_cellphone(message):
        logging.warning("This email is not from a cellphone")
        return False
      
      if not self.has_attachments(message):
        logging.warning('This email has no attachements.')
        return False
        
      attachments = []
      if isinstance(message.attachments[0], basestring):
        attachments = [message.attachments]
      else:
        attachments = message.attachments
      
      for filename, content in attachments:
        key = str(time.mktime(datetime.datetime.now().timetuple()))+"_"+str(message.sender)+"_"+str(filename)
        self.upload_content_to_s3(
          key.replace(' ',''),
          content.payload.decode(content.encoding),
          'multipart/form-data'
        )
        record = YeahRecord(
          author=message.sender,
          timestamp=int(time.mktime(datetime.datetime.now().timetuple())),
          s3_key=key.replace(' ','')
        )
        record.put()
      return self.json([message.sender])
    
    def is_cellphone(self,message):
      logging.info("#### EmailReceiver.is_cellphone")
      #do not know how to effectively test for this now
      #will disregard for the time being
      return True
      
    def has_attachments(self,message):
      logging.info("#### EmailReceiver.has_attachments")
      try:
        if message.attachments:
          return True
      except exceptions.AttributeError:
        return False
    

    def upload_content_to_s3(self,key,content,content_type='text/plain'):
      logging.info("#### EmailReceiver.upload_content_to_s3")
      conn = GoogleS3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
      conn.put(
        'yeahyeahyeahyeahyeah',
        key,
        GoogleS3.S3Object(str(content)),
        { 'Content-Type': content_type }).message
      